package com.huike.business.service.impl;


import com.fasterxml.jackson.databind.util.BeanUtil;
import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商机跟进记录Service业务层处理
 * 
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {
    @Autowired
    private TbBusinessMapper tbBusinessMapper;
    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;


    /**
     * 新增商机跟进记录
     *
     * @param businessTrackVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BusinessTrackVo businessTrackVo) {
        TbBusiness tbBusiness = new TbBusiness();
        BeanUtils.copyProperties(businessTrackVo,tbBusiness);
        // 修改商机
        tbBusiness.setId(businessTrackVo.getBusinessId());
        tbBusinessMapper.updateTbBusiness(tbBusiness);

        // 添加商机跟进记录
        TbBusinessTrackRecord tbBusinessTrackRecord = new TbBusinessTrackRecord();
        BeanUtils.copyProperties(businessTrackVo,tbBusinessTrackRecord);
        String username = SecurityUtils.getUsername();
        tbBusinessTrackRecord.setCreateBy(username);
        tbBusinessTrackRecordMapper.insertTbBusinessTrackRecord(tbBusinessTrackRecord);
    }

    /**
     * 查询商机跟进记录列表
     *
     * @param id
     * @return
     */
    @Override
    public List<TbBusinessTrackRecord> listByBusinessId(Long id) {
        List<TbBusinessTrackRecord> recordslist = tbBusinessTrackRecordMapper.listByBusinessId(id);
        for (TbBusinessTrackRecord record : recordslist) {
            String keyItems = record.getKeyItems();
            List<String> keys = record.getKeys();
            String[] strings = keyItems.split(",");
            for (String string : strings) {
                String key = tbBusinessTrackRecordMapper.getKeyByKeyItem(Integer.parseInt(string));
                keys.add(key);
            }
            record.setKeys(keys);
        }
        return recordslist;
    }



}
